import { response } from '@/apps';
import prisma from '@/components/server/utils/prisma';
import type { Post } from '@prisma/client';
import type { NextApiRequest, NextApiResponse } from 'next';

export type DataItem = Post & {
  categories: { category: { id: number; cat: string } }[];
};

export type Data = {
  post?: Array<DataItem>;
  total?: number;
} & response;

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  const {
    page,
    size,
    catId: categoryId,
    title,
  }: { page: number; size: number; catId?: number; title?: string } = req.body;
  const post = await prisma.post.findMany({
    orderBy: [{ id: 'desc' }],
    where: {
      title: { contains: title },
      categories: {
        some: {
          categoryId: categoryId,
        },
      },
      // categories: {},
    },
    select: {
      id: true,
      title: true,
      createAt: true,
      updatedAt: true,
      authorId: true,
      categories: {
        select: {
          categoryId: false,
          category: { select: { id: true, cat: true } },
        },
      },
    },
    take: size ?? 10,
    skip: ((page ?? 1) - 1) * (size ?? 10),
  });
  const total = await prisma.post.count({
    where: {
      title: { contains: title },
      categories: {
        some: {
          categoryId: categoryId,
        },
      },
    },
  });
  if (post) {
    res.status(200).json({
      post,
      total,
      code: 0,
    });
  } else {
    res.status(404).send({ code: -1, msg: 'error' });
  }
}
